<template>
  <div
    class="design-shape"
    :class="{ active: element.focused }"
    :style="{
      width: `${element.w}px`,
      height: `${element.h}px`,
      zIndex: element.z,
      transform: `translate(${element.x}px, ${element.y}px) rotate(${element.r}deg)`,
    }"
    @mousedown.stop="handleMouseDown"
    @click="handleContext(element)"
    @contextmenu="handleContextMenu($event, element)"
  >
    <template v-if="element.focused">
      <!-- 变换 -->
      <div
        class="design-shape-point"
        :ref="name"
        v-for="(name, index) in point"
        :key="index"
        :style="initPoint(name)"
        @mousedown="handleMouseDownOnPoint(name, $event)"
      />
      <!-- 旋转 -->
      <div class="design-shape-rotate" @mousedown="handleRotate">
        <svg
          t="1661068506477"
          class="icon rotate"
          viewBox="0 0 1024 1024"
          p-id="6508"
          width="14"
          height="14"
        >
          <path
            d="M768.938667 256A361.898667 361.898667 0 0 0 512 149.333333C311.701333 149.333333 149.333333 311.701333 149.333333 512s162.368 362.666667 362.666667 362.666667 362.666667-162.368 362.666667-362.666667h85.333333c0 247.424-200.576 448-448 448S64 759.424 64 512 264.576 64 512 64c122.88 0 237.226667 49.898667 320 134.4V64h85.333333v277.333333H640v-85.333333h128.938667z"
            p-id="6509"
            fill="#59c7f9"
          ></path>
        </svg>
      </div>
    </template>
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: {
    zoom: Number,
    status: {
      type: Boolean,
      default: true,
    },
    element: {
      type: Object,
    },
    lightInfo: {
      type: Object,
    },
  },
  data() {
    return {
      point: ["tl", "tr", "br", "bl"],
      isMove: false,
      lineMove: {
        type: null,
        startWidth: 0,
        startHeight: 0,
        startX: 0,
        startY: 0,
        x: 0,
        y: 0,
      },
      // 组件原始的宽高
      origin: null,
    };
  },
  methods: {
    handleContextMenu(e, data) {
      e.stopPropagation();
      e.preventDefault();
      this.$store.dispatch("design/settingMenu", {
        show: true,
        top: e.clientY,
        left: e.clientX,
      });
      this.$store.dispatch("design/selectComplex", data);
    },
    handleContext(data) {
      // 点击事件
      this.$store.dispatch("design/selectComplex", data);
      this.$emit("handleContext", data);
    },
    // 组件变换
    handleMouseDownOnPoint(point, e) {
      // console.log(e)
      let screenTop = document
        .getElementById("design")
        .getBoundingClientRect().top;
      let screenLeft = document
        .getElementById("design")
        .getBoundingClientRect().left;
      e.stopPropagation();
      e.preventDefault();
      // 组件初始宽高
      const startWidth = this.element.w;
      const startHeight = this.element.h;
      const startX = e.clientX;
      const startY = e.clientY;
      if (this.element.name === "tool-combination") {
        console.log("记录拖拽前的原始宽高");
        // 记录拖拽前的原始宽高
        this.origin = {
          w: this.element.w,
          h: this.element.h,
        };
        this.$store.dispatch("design/setOrigin", this.origin);
      }
      // 组件宽高比
      const proportion = this.element.w / this.element.h;
      // 组件中心点
      const center = {
        x: this.element.x + this.element.w / 2,
        y: this.element.y + this.element.h / 2,
      };

      const pointRect = e.target.getBoundingClientRect();
      // 当前点击圆点相对于画布的中心坐标
      const designDom = document
        .getElementById("design")
        .getBoundingClientRect();
      const curPoint = {
        x: Math.round(
          pointRect.left - designDom.left + e.target.offsetWidth / 2
        ),
        y: Math.round(
          pointRect.top - designDom.top + e.target.offsetHeight / 2
        ),
      };

      // 获取对称点的坐标
      const symmetricPoint = {
        x: center.x - (curPoint.x - center.x),
        y: center.y - (curPoint.y - center.y),
      };

      let isFirst = true;
      const move = (moveEvent) => {
        // 第一次点击时也会触发 move，所以会有“刚点击组件但未移动，组件的大小却改变了”的情况发生
        // 因此第一次点击时不触发 move 事件
        if (isFirst) {
          isFirst = false;
          return;
        }
        // 鼠标移动距离
        const moveY = moveEvent.clientY - startY;
        const moveX = moveEvent.clientX - startX;
        // console.log(moveY, moveX)
        if (point === this.point[0]) {
          // 左上
          console.log("左上");
        }

        if (point === this.point[2]) {
          // 右下
          console.log("右下");
          this.element.w = startWidth + moveX / this.zoom;
          this.element.h = startHeight + moveY / this.zoom;
        }
      };

      const up = () => {
        // 释放组合元素当前缩放比例
        if (this.element.name === "tool-combination") {
          this.updateCombination();
        }
        document.removeEventListener("mousemove", move);
        document.removeEventListener("mouseup", up);
      };

      document.addEventListener("mousemove", move);
      document.addEventListener("mouseup", up);
    },
    // 修改组合元素子元素的位置宽高值
    updateCombination() {
      // console.log('修改组合元素子元素的位置宽高值')
      const xscale = this.element.w / this.origin.w;
      const yscale = this.element.h / this.origin.h;
      this.element.config.childs.forEach((item, index) => {
        item.x = item.x * xscale;
        item.w = item.w * xscale;
        item.y = item.y * yscale;
        item.h = item.h * yscale;
      });
      this.origin = null;
      this.element.xscale = 1;
      this.element.yscale = 1;
    },
    // 组件移动
    handleMouseDown(event) {
      const startY = event.clientY;
      const startX = event.clientX;

      if (this.element.lock) {
        // console.log('组件已锁定')
        return;
      }

      const startTop = Number(this.element.y);
      const startLeft = Number(this.element.x);

      const move = (moveEvent) => {
        const curX = moveEvent.clientX;
        const curY = moveEvent.clientY;
        // 设置组件移动位置
        this.element.y = (curY - startY) / this.zoom + startTop;
        this.element.x = (curX - startX) / this.zoom + startLeft;
        // console.log(this.element.x,'this.element.x');
        this.$emit("exportFun", this.element);
        this.isMove = true;
      };

      const up = () => {
        if (this.isMove) {
          // if(this.element.config.attr){
          //   let flag = false
          //   this.element.config.attr.forEach((ele)=>{
          //     if(ele.formType == "layout-span"){
          //       flag = ele.data.status;
          //     }
          //   })
          //   if(flag){
              
          //   }
          // }
          this.element.x = this.lightInfo.x;
          this.element.y = this.lightInfo.y;
          this.element.w = this.lightInfo.w;
          this.element.h = this.lightInfo.h;
          this.$parent.isHuaRu = -1;
          this.$parent.gridInfo.width = 0;
          this.$parent.gridInfo.height = 0;
          this.$parent.complexList.forEach((ele, index, arr) => {
            if (
              this.element.x == ele.x &&
              this.element.y == ele.y &&
              this.element.id != ele.id
            ) {
              arr.splice(index, 1);
            }
          });
        }
        this.isMove = false;
        document.removeEventListener("mousemove", move);
        document.removeEventListener("mouseup", up);
      };

      document.addEventListener("mousemove", move);
      document.addEventListener("mouseup", up);
    },
    // 组件旋转
    handleRotate(event) {
      event.preventDefault();
      event.stopPropagation();
      let screenTop = document
        .getElementById("design")
        .getBoundingClientRect().top;
      let screenLeft = document
        .getElementById("design")
        .getBoundingClientRect().left;
      // 获取起始点
      const startX = (event.clientX - screenLeft) / this.zoom;
      const startY = (event.clientY - screenTop) / this.zoom;
      // 组件中心点
      const centerX = this.element.x + this.element.w / 2;
      const centerY = this.element.y + this.element.h / 2;

      const startRotate = this.element.r;
      // 旋转前的角度
      const rotateDegreeBefore =
        Math.atan2(startY - centerY, startX - centerX) / (Math.PI / 180);
      // console.log(startX, startY, centerX, centerY, rotateDegreeBefore)
      const move = (moveEvent) => {
        const curX = (moveEvent.clientX - screenLeft) / this.zoom;
        const curY = (moveEvent.clientY - screenTop) / this.zoom;
        // 旋转后的角度
        const rotateDegreeAfter =
          Math.atan2(curY - centerY, curX - centerX) / (Math.PI / 180);
        // 设置组件旋转角度
        this.element.r = startRotate + rotateDegreeAfter - rotateDegreeBefore;
      };
      const up = () => {
        document.removeEventListener("mousemove", move);
        document.removeEventListener("mouseup", up);
      };
      document.addEventListener("mousemove", move);
      document.addEventListener("mouseup", up);
    },
    initPoint(name) {
      if (name == "tl") {
        return {
          top: 0,
          left: 0,
          transform: `translate(-50%,-50%)`,
          cursor: `nw-resize`,
        };
      } else if (name == "tr") {
        return {
          top: 0,
          right: 0,
          transform: `translate(50%,-50%)`,
          cursor: `ne-resize`,
        };
      } else if (name == "bl") {
        return {
          bottom: 0,
          left: 0,
          transform: `translate(-50%,50%)`,
          cursor: `ne-resize`,
        };
      } else if (name == "br") {
        return {
          bottom: 0,
          right: 0,
          transform: `translate(50%,50%)`,
          cursor: `se-resize`,
        };
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.design-shape {
  position: absolute;
  box-sizing: border-box;
}

.active {
  outline: 1px solid #59c7f9;
  user-select: none;
}

.design-shape-point {
  position: absolute;
  background: #fff;
  border: 1px solid #59c7f9;
  width: 8px;
  height: 8px;
  min-width: 8px;
  min-height: 8px;
  border-radius: 50%;
  z-index: 1;
}

.design-shape-rotate {
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translateX(-50%);
  display: inline-block;
  width: 15px;
  height: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.rotate {
  cursor: pointer;
  transform: rotate(45deg);
}
</style>
